package com.yike.order.service.impl;

import com.github.wxpay.sdk.WXPay;
import com.yike.common.exception.BusinessException;
import com.yike.common.tool.IpUtil;
import com.yike.common.tool.StringUtil;
import com.yike.order.param.WxPayRequestParam;
import com.yike.order.param.WxQueryRequestParam;
import com.yike.order.param.WxRefundRequestParam;
import com.yike.order.service.WxPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class WxPayServiceImpl implements WxPayService {

    @Autowired
    WXPay wxpay;

    @Override
    public Map<String, String> microPay(WxPayRequestParam params) {
        Map<String, String> resp = null;
        try {
            Map<String, String> data = new HashMap<>();
            data.put("body", params.getBody());
            data.put("out_trade_no", params.getOutTradeNo());
            data.put("total_fee", params.getTotalFee());
            data.put("spbill_create_ip", IpUtil.getRequestIp());
            data.put("auth_code", params.getAuthCode());  // 此处指定为扫码支付
            resp = wxpay.microPay(data);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BusinessException(500, e.getMessage());
        }
        return resp;
    }

    @Override
    public Map<String, String> refund(WxRefundRequestParam params) {
        Map<String, String> resp = null;
        try {
            Map<String, String> data = new HashMap<>();
            data.put("out_trade_no", params.getOutTradeNo());
            data.put("out_refund_no", params.getOutRefundNo());
            data.put("total_fee", params.getTotalFee().toString());
            data.put("refund_fee", params.getRefundFee().toString());
            if (StringUtil.isNotBlank(params.getRefundDesc())) {
                data.put("refund_desc", params.getRefundDesc());
            }
            resp = wxpay.refund(data);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BusinessException(500, e.getMessage());
        }
        return resp;
    }

    @Override
    public Map<String, String> orderQuery(WxQueryRequestParam params) {
        Map<String, String> resp = null;
        try {
            Map<String, String> data = new HashMap<>();
            data.put("out_trade_no", params.getOutTradeNo());
            resp = wxpay.orderQuery(data);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BusinessException(500, e.getMessage());
        }
        return resp;
    }
}
